<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\model;


use think\Db;
use think\Model;
use traits\model\SoftDelete;


class AgencyOrder extends Model
{
    
    protected $table = 'agency_order';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'updata_time';
    protected $autoWriteTimestamp = true;
    /**自营详情
     * Summary of info
     * @param mixed $agencyOrderId
     * @return array{code: int, data: array|array{code: int, msg: string}}
     */
    public function info($agencyOrderId)
    {
        $agencyTask     = new AgencyTask();
        $agencyOrder    = $this->where('id', $agencyOrderId)->find();
        if(empty($agencyOrder)){
            return ['code'=>300,'msg'=>"等待设计师操作"];
        }
        $cost           = $agencyTask->where('delete_time', 0)->where('agency_order_id', $agencyOrderId)->field('sum(total_cost) as totalCost,sum(manual_cost) as manualCost,cooperation_type,app_user_start_time,agency_staff_id')->select();
       
        $filteredArr = array_filter(array_column($cost,'agency_staff_id'), function ($value) {
            return $value > 0;
        });
        if (count($filteredArr) == 0) {
           
          return $this->nonSelfOperated($agencyOrderId);
        } 
        //测量时间
        //预计
        $measurementTimeExpectedTo = empty($agencyOrder['measurement_time']) ? '' : date('Y-m-d', $agencyOrder['measurement_time']);
        //实际
        $measurementTimeReality = empty($agencyOrder['measurement_actual_time']) ? '' : date('Y-m-d', $agencyOrder['measurement_actual_time']);
        //状态
        $measurementTimeState = empty($measurementTimeReality) ? 0 : 3;
        //方案完成时间
        //预计
        $solutionCompletionTimeExpectedTo = empty($agencyOrder['solution_completion_time']) ? '' : date('Y-m-d', $agencyOrder['solution_completion_time']);
        //实际
        $solutionCompletionTimeReality = empty($agencyOrder['measurement_actual_time']) ? '' : date('Y-m-d', $agencyOrder['measurement_actual_time']);
        //状态
        $solutionCompletionTimeState = empty($solutionCompletionTimeReality) ? 0 : 3;
        
        //方案确认时间
        //预计
        $storeConfirmTimeExpectedTo = "";
        //实际
        $storeConfirmTimeReality = empty($agencyOrder['store_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['store_confirm_time']);
        //状态
        $storeConfirmTimeState=empty($storeConfirmTimeReality) ?0: 3;
        if($agencyOrder['status']==2){
            $storeConfirmTimeState =1;
        }
        //0未开始1方案确认2去验收3已完成
        
        //供应商产确认时间
        //预计
        $agencyConfirmTimeExpectedTo = "";
        //实际
        $agencyConfirmTimeReality = empty($agencyOrder['agency_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['agency_confirm_time']);
        //状态
        $agencyConfirmTimeState =  empty($agencyConfirmTimeReality) ? 0 : 3;;
       
        
        
        //设计师审核   供应链经理审核
        //预计
        $designerConfirmTimeExpectedTo = "";
        //实际
        $designerConfirmTimeReality = empty($agencyOrder['designer_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['designer_confirm_time']);
        //状态
        $designerConfirmTimeState = empty($designerConfirmTimeReality) ? 0 : 3;
        //供应商排单确认
        //预计
        $schedulingConfirmTimeExpectedTo = empty($agencyOrder['generation_time']) ? '' : date('Y-m-d', $agencyOrder['generation_time']);
        //实际
        $schedulingConfirmTimeReality = empty($agencyOrder['scheduling_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['scheduling_confirm_time']);
        //状态
        $schedulingConfirmTimeState = empty($schedulingConfirmTimeReality) ? 0 : 3;
        
        //配送时间
        //预计
        $deliverableTimeExpectedTo = "";
        //实际
        $deliverableTimeReality = empty($agencyOrder['deliverable_time']) ? '' : date('Y-m-d', $agencyOrder['deliverable_time']);
        //状态
        $deliverableTimeState = empty($deliverableTimeReality) ? 0 : 3;
        //配送完成
        //预计
        $deliveryCompletionTimeExpectedTo = empty($agencyOrder['generation_completion_time']) ? '' : date('Y-m-d', $agencyOrder['generation_completion_time']);
        //实际
        $deliveryCompletionTimeReality = empty($agencyOrder['delivery_completion_time']) ? '' : date('Y-m-d', $agencyOrder['delivery_completion_time']);
        //状态
        $deliveryCompletionTimeState = empty($deliveryCompletionTimeReality) ? 0 : 3;
        
        //安装开始时间
        //预计
        $startAtTimeExpectedTo = "";
        //实际
        $startAtReality = empty($cost[0]['app_user_start_time']) ? '' : date('Y-m-d', $cost[0]['app_user_start_time']);
        //状态
        $startAtTimeState = empty($startAtReality) ? 0 : 3;
        
        //安装完成时间
        //预计
        $completionTimeExpectedTo = empty($agencyOrder['installation_time']) ? '' : date('Y-m-d', $agencyOrder['installation_time']);
        //实际
        $completionTimeReality = empty($agencyOrder['completion_time']) ? '' : date('Y-m-d', $agencyOrder['completion_time']);
        //状态
        $completionTimeState = empty($completionTimeReality) ? 0 : 3;
        
        //店长验收
        //实际
        $acceptancePassTimeReality = empty($agencyOrder['acceptance_pass_time']) ? '' : date('Y-m-d', $agencyOrder['acceptance_pass_time']);
        //状态
        $acceptancePassTimeState =0;
        if(empty($agencyOrder['completion_time']) && $agencyOrder['status']==13){
            $acceptancePassTimeState =2;
        }
        if(!empty($agencyOrder['completion_time']) && ($agencyOrder['status']==14 || $agencyOrder['status']==15)){
            $acceptancePassTimeState =3;
        }
       
        
        //供应商结算
        //预计
        $lastPaymentConfirmTimeExpectedTo = "";
        //实际
        $lastPaymentConfirmTimeReality = empty($agencyOrder['last_payment_confirm_time']) ? '': date('Y-m-d', $agencyOrder['last_payment_confirm_time']);
        //状态
        $lastPaymentConfirmTimeState = empty($lastPaymentConfirmTimeReality) ? 0 : 3;
        
        
        $list = [
            [
                'title' => "测量及方案确认",
                'data' => [
                    [
                        'title' => "测量时间:",
                        'state' => $measurementTimeState,
                        'estimatedTime' => $measurementTimeExpectedTo,//预计时间
                        'completeTime' => $measurementTimeReality,//完成时间
                    ],
                    [
                        'title' => "方案完成时间:",
                        'state' => $solutionCompletionTimeState,
                        'estimatedTime' => $solutionCompletionTimeExpectedTo,//预计时间
                        'completeTime' => $solutionCompletionTimeReality,//完成时间
                    ],
                    [
                        'title' => "方案确认时间:",
                        'state' => $storeConfirmTimeState,
                        'estimatedTime' => $storeConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $storeConfirmTimeReality,//完成时间
                        'img' => empty($agencyOrder['attachment']) ? null : json_decode($agencyOrder['attachment'], true),
                        "totalCost" =>  $cost[0]['totalCost'],
                        "manualCost" => $cost[0]['manualCost'],
                    ],
                    
                ],
                
            ],
            [
                'title' => "下单及生产",
                'data' => [
                    [
                        'title' => "供应商确认:",
                        'state' => $agencyConfirmTimeState,
                        'estimatedTime' => $agencyConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $agencyConfirmTimeReality,//完成时间
                    ],
                    [
                        'title' => "设计师审核:",
                        'state' => $designerConfirmTimeState,
                        'estimatedTime' => $designerConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $designerConfirmTimeReality,//完成时间
                    ],
                    [
                        'title' => "供应链经理审核:",
                        'state' => $designerConfirmTimeState,
                        'estimatedTime' => $designerConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $designerConfirmTimeReality,//完成时间
                    ], [
                        'title' => "供应商排单确认:",
                        'state' => $schedulingConfirmTimeState,
                        'estimatedTime' => $schedulingConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $schedulingConfirmTimeReality,//完成时间
                    ],
                
                
                ],
            ],
            [
                'title' => "配送及施工",
                'data' => [
                    [
                        'title' => "配送时间:",
                        'state' => $deliverableTimeState,
                        'estimatedTime' => $deliverableTimeExpectedTo,//预计时间
                        'completeTime' => $deliverableTimeReality,//完成时间
                    ],
                    [
                        'title' => "配送完成:",
                        'state' => $deliveryCompletionTimeState,
                        'estimatedTime' => $deliveryCompletionTimeExpectedTo,//预计时间
                        'completeTime' => $deliveryCompletionTimeReality,//完成时间
                    ],
                    [
                        'title' => "安装开始时间:",
                        'state' => $startAtTimeState,
                        'estimatedTime' => $startAtTimeExpectedTo,//预计时间
                        'completeTime' => $startAtReality,//完成时间
                    ],
                    ['title' => "安装完成时间:",
                        'state' => $completionTimeState,
                        'estimatedTime' => $completionTimeExpectedTo,//预计时间
                        'completeTime' => $completionTimeReality,//完成时间
                    ],
                    [
                        'title' => "店长验收:",
                        'state' => $acceptancePassTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $acceptancePassTimeReality,//完成时间
                    ],
                ]
            ],
            [
                'title' => "结算",
                'data' => [
                    [
                        'title' => "供应商结算:",
                        'state' => $lastPaymentConfirmTimeState,
                        'estimatedTime' => $lastPaymentConfirmTimeExpectedTo,//预计时间
                        'completeTime' => $lastPaymentConfirmTimeReality,//完成时间
                    ],
                ]
            ]
        ];
        foreach ($list as $k => $item) {
            foreach ($item['data'] as $key => $v) {
            
                if ($cost[0]['cooperation_type'] == 1 && $v['title'] == "供应链经理审核:") {
                    unset($list[$k]['data'][$key]);
                   
                }
            }
            $list[$k]['data']=array_merge($list[$k]['data']);
        }
        return ['code'=>200,'data'=>$list,'type'=>2];
        
    }
      /**非自营详情
     * Summary of info
     * @param mixed $agencyOrderId
     * @return array{code: int, data: array|array{code: int, msg: string}}
     */
    public function nonSelfOperated($agencyOrderId)
    {
        $agencyTask     = new AgencyTask();
        $agencyOrder    = $this->where('id', $agencyOrderId)->find();
        if(empty($agencyOrder)){
            return ['code'=>300,'msg'=>"等待设计师操作"];
        }
        $cost           = $agencyTask->join('capital', 'capital.capital_id=agency_task.capital_id', 'left')->where('delete_time', 0)->where('agency_order_id', $agencyOrderId)->field('if(user_input_cost >0 and user_input_cost !=total_cost,concat(capital.class_b,":",total_cost,"元（由",user_input_cost,"元修改为",total_cost,"元"),concat(capital.class_b,":",total_cost,"元" ))as content,if(user_input_cost >0,concat(capital.class_b,":",user_input_cost,"元"),concat(capital.class_b,":",total_cost,"元")) as initialContent,app_user_start_time,concat(capital.class_b,":",total_cost,"元") as storeManagerConfirmation')->select();
        
      
        //派单时间
        $dispatchTime=$agencyOrder['create_time'];
        $dispatchState=empty($agencyOrder['create_time'])?0:3;

        //配送时间
        //实际
        $deliverableTimeReality = empty($agencyOrder['deliverable_time']) ? '' : date('Y-m-d', $agencyOrder['deliverable_time']);
        //状态
        $deliverableTimeState = empty($deliverableTimeReality) ? 0 : 3;

         //配送完成
        //预计
        //实际
        $deliveryCompletionTimeReality = empty($agencyOrder['delivery_completion_time']) ? '' : date('Y-m-d', $agencyOrder['delivery_completion_time']);
        //状态
        $deliveryCompletionTimeState = empty($deliveryCompletionTimeReality) ? 0 : 3;

        //供应商接单时间
        //预计
      
        //实际
        $agencyConfirmTimeReality = empty($agencyOrder['agency_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['agency_confirm_time']);
        //状态
        $agencyConfirmTimeState =  empty($agencyConfirmTimeReality) ? 0 : 3;
        
        //店长确认时间
        $storeConfirmTimeReality = empty($agencyOrder['store_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['store_confirm_time']);
        //状态
        $storeConfirmTimeState=empty($storeConfirmTimeReality) ?0: 3;
        //用户确认时间:
        $userConfirmTime = empty($agencyOrder['user_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['user_confirm_time']);
        //状态
         $userConfirmTimeState=empty($userConfirmTime) ?0: 3;
         //安装开始时间
        //预计
       
        //实际
        $startAtReality = empty($cost[0]['app_user_start_time']) ? '' : date('Y-m-d', $cost[0]['app_user_start_time']);
        //状态
        $startAtTimeState = empty($startAtReality) ? 0 : 3;
        //供应链经理审核时间:
       
        //实际
        $designerConfirmTimeReality = empty($agencyOrder['designer_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['designer_confirm_time']);
        //状态
        $designerConfirmTimeState = empty($designerConfirmTimeReality) ? 0 : 3;
        //供应商排单确认
        //实际
        $schedulingConfirmTimeReality = empty($agencyOrder['scheduling_confirm_time']) ? '' : date('Y-m-d', $agencyOrder['scheduling_confirm_time']);
        //状态
        $schedulingConfirmTimeState = empty($schedulingConfirmTimeReality) ? 0 : 3;
        //店长验收
        //实际
        $acceptancePassTimeReality = empty($agencyOrder['acceptance_pass_time']) ? '' : date('Y-m-d', $agencyOrder['acceptance_pass_time']);
        //状态
        $acceptancePassTimeState =0;
        if(empty($agencyOrder['completion_time']) && $agencyOrder['status']==13){
            $acceptancePassTimeState =2;
        }
        if(!empty($agencyOrder['completion_time']) && ($agencyOrder['status']==14 || $agencyOrder['status']==15)){
            $acceptancePassTimeState =3;
        }
        $agency_task = \db('agency_task', config('database.zong'))->join('agency', 'agency.agency_id=agency_task.agency_id', 'left')->join('order', 'order.order_id=agency_task.order_id', 'left')->where('agency_task.agency_order_id', $agencyOrderId)->field('agency_task.total_cost,agency.agency_name,agency_task.agency_id')->where('agency_task.status','<>',2)->select();
        $agency_order_sub           = \db('agency_order_sub')->where('agency_order_sub.agency_order_id', $agencyOrderId)->select();
        $agencyOrderSubAttachment=[];
        foreach($agency_order_sub as $value){
           if(!empty($value['attachment'])){
            $logoList=json_decode($value['attachment'],true);
            $agencyOrderSubAttachment=array_merge($agencyOrderSubAttachment, $logoList);
           }
        }
        $agencyOrderSubAttachment=empty( $agencyOrderSubAttachment)?null: $agencyOrderSubAttachment;
        $result      = array();
        foreach ($agency_task as $k => $v) {
         $result[$v['agency_id']][] = $v;
        }
        $resultData     = array();
       
        foreach ($result as $k => $item) {
            $first_reimbursement_id=[];
            $reimbursement_agency= db('reimbursement_agency')->join('reimbursement_relation','reimbursement_agency.reimbursement_relation_id=reimbursement_relation.relation_id','left')
           
            
            ->where('reimbursement_agency.agency_order_id',$agencyOrderId)->join('reimbursement','reimbursement.id=reimbursement_relation.reimbursement_id','left')->field('reimbursement_agency.*,reimbursement_relation.*')->where('reimbursement.status', 1)->where('reimbursement_relation.bank_id', $k)->find();
           
        
            $audit_materials= db('audit_materials')->join('capital','capital.acceptance=audit_materials.materials_id','left')->whereIn('capital.capital_id',$reimbursement_agency['capital_id'])->column('prove');
          
            $prove=[];
            foreach($audit_materials as $it){
               $logoList=unserialize($it);
               $prove=array_merge($prove, $logoList);
            }
            foreach($agency_order_sub as $value){
                if($value['agency_id']==$k){
                    $first_reimbursement_id[]=$value['first_reimbursement_id'];
                    }
            }
            $incre_money=$reimbursement_agency['money'];
            $reimbursementRelationMoney=db('reimbursement_relation')->join('reimbursement','reimbursement.id=reimbursement_relation.reimbursement_id','left')->where('reimbursement.status', 1)->whereIn('reimbursement_relation.reimbursement_id',$first_reimbursement_id)->where('bank_id', $k)->sum('reimbursement_relation.money');
            $total_cost=array_sum(array_column($item,'total_cost'));
            $balance_payment=bcsub($total_cost,$reimbursementRelationMoney,2);
            $resultData[]=[
                // 'reimbursementRelationMoney' =>$reimbursementRelationMoney,
                // 'total_cost'=>array_sum(array_column($item,'total_cost')),
                // 'name'=>$item[0]['agency_name'],
                'reason'=> $reimbursement_agency['abnormal_settlement_reason'],
                'prove'=>$prove,
                // 'agency_incre'=> $incre_money,
                'title'=>$item[0]['agency_name'].":尾款修改为：".$incre_money."元（此尾款由".$balance_payment."元修改为".$incre_money."元）"
            ];
         
        }
      
       
        
        //尾款调整
        $agency_incre           = db('agency_incre')->where('agency_order_id',$agencyOrderId)->select();
        //供应商结算
        //实际
        $lastPaymentConfirmTimeReality = empty($agencyOrder['last_payment_confirm_time']) ? '': date('Y-m-d', $agencyOrder['last_payment_confirm_time']);
        //状态
        $lastPaymentConfirmTimeState = empty($lastPaymentConfirmTimeReality) ? 0 : 3;
        $disclose=json_decode($agencyOrder['disclose'],true);//派单附图#
        $discloseImg=[];
        if(!empty($disclose)){
            foreach($disclose as $k=>$it){
                $discloseImg[$k]['title']='';   
                $discloseImg[$k]['url']=$it;   
            }
        }
        
      
        $list = [
            [
                'title' => "下单及生产",
                'data' => [
                    [
                        'title' => "派单时间:",
                        'state' => $dispatchState,
                        'estimatedTime' =>'',//预计时间
                        'completeTime' => $dispatchTime,//完成时间
                        'remark'=> empty($dispatchTime) ? null :$agencyOrder['remark'],//派单备注
                        'img'=>empty($discloseImg)?null:$discloseImg,//派单附图#
                        "mainMaterialCost" =>array_column($cost,'initialContent'),
                    ],
                    [
                        'title' => "供应商接单时间:",
                        'state' => $agencyConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $agencyConfirmTimeReality,//完成时间
                      
                        'img' => empty($agencyConfirmTimeReality) ? null :$agencyOrderSubAttachment,
                        "mainMaterialCost" =>empty($agencyConfirmTimeReality)?null:array_column($cost,'content'),
                    ],
                    [
                        'title' => "店长确认时间:",
                        'state' => $storeConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $storeConfirmTimeReality,//完成时间
                       
                        'img' => empty($storeConfirmTimeReality) ? null :  $agencyOrderSubAttachment,
                        "mainMaterialCost" =>empty($storeConfirmTimeReality)?null:array_column($cost,'storeManagerConfirmation'),
                    ],
                    [
                        'title' => "用户确认时间:",
                        'state' => $userConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $userConfirmTime,//完成时间
                       
                    ],
                    [
                        'title' => "供应链经理审核时间:",
                        'state' => $designerConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $designerConfirmTimeReality,//完成时间
                        
                        
                    ],
                    [
                        'title' => "供应商排单时间:",
                        'state' => $schedulingConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $schedulingConfirmTimeReality,//完成时间
                        
                    ]
                    
                ],
                
            ],
            [
                'title' => "配送及施工",
                'data' => [
                    [
                        'title' => "配送时间:",
                        'state' => $deliverableTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $deliverableTimeReality,//完成时间
                        
                    ],
                    [
                        'title' => "配送完成:",
                        'state' => $deliveryCompletionTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $deliveryCompletionTimeReality,//完成时间
                        
                    ],
                    [
                        'title' => "安装完成时间:",
                        'state' => $startAtTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $startAtReality,//完成时间
                        
                    ], [
                        'title' => "店长验收时间:",
                        'state' => $acceptancePassTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $acceptancePassTimeReality,//完成时间
                        'list'=>empty($acceptancePassTimeReality)?null:$resultData
                        
                    ],
                
                
                ],
            ],

                    
            [
                'title' => "结算",
                'data' => [
                    [
                        'title' => "供应商结算:",
                        'state' => $lastPaymentConfirmTimeState,
                        'estimatedTime' => '',//预计时间
                        'completeTime' => $lastPaymentConfirmTimeReality,//完成时间
                    ],
                ]
            ]
        ];

        return ['code'=>200,'data'=>$list,'type'=>1];
        
    }

    
}





